package ca

import (
	"errors"
	"strings"

	"github.com/casbin/casbin/v2/model"
	"github.com/casbin/casbin/v2/persist"

	zd "gitee.com/haifengat/zorm-dm"
)

type Adapter struct {
	isFiltered bool
}

// CasbinRule  .
type CasbinRule struct {
	Ptype string `zorm:"type:varchar(100);index;not null;default:''"`
	V0    string `zorm:"type:varchar(100);index;not null;default:''"`
	V1    string `zorm:"type:varchar(100);index;not null;default:''"`
	V2    string `zorm:"type:varchar(100);index;not null;default:''"`
	V3    string `zorm:"type:varchar(100);index;not null;default:''"`
	V4    string `zorm:"type:varchar(100);index;not null;default:''"`
	V5    string `zorm:"type:varchar(100);index;not null;default:''"`
	zd.Entity
}

// Filter  .
type Filter struct {
	Ptype []string
	V0    []string
	V1    []string
	V2    []string
	V3    []string
	V4    []string
	V5    []string
}

func (f *Filter) toMap() map[string]any {
	mp := make(map[string]any)
	if len(f.Ptype) > 0 {
		mp["ptype"] = f.Ptype
	}
	if len(f.V0) > 0 {
		mp["V0"] = f.V0
	}
	if len(f.V1) > 0 {
		mp["V1"] = f.V1
	}
	if len(f.V2) > 0 {
		mp["V2"] = f.V2
	}
	if len(f.V3) > 0 {
		mp["V3"] = f.V3
	}
	if len(f.V4) > 0 {
		mp["V4"] = f.V4
	}
	if len(f.V5) > 0 {
		mp["V5"] = f.V5
	}
	return mp
}

// NewAdapter is the constructor for Adapter.
func NewAdapter(dataSourceName string) (*Adapter, error) {
	a := &Adapter{}

	zd.SchemaName = "casbin"
	if _, err := zd.InitDao(dataSourceName); err != nil {
		return nil, err
	}

	if err := zd.CreateSchema(zd.SchemaName); err != nil {
		return nil, err
	}
	if err := zd.CreateTable[CasbinRule](); err != nil {
		return nil, err
	}
	return a, nil
}

func loadPolicyLine(line CasbinRule, model model.Model) {
	var p = []string{line.Ptype,
		line.V0, line.V1, line.V2, line.V3, line.V4, line.V5}
	var lineText string
	if line.V5 != "" {
		lineText = strings.Join(p, ", ")
	} else if line.V4 != "" {
		lineText = strings.Join(p[:6], ", ")
	} else if line.V3 != "" {
		lineText = strings.Join(p[:5], ", ")
	} else if line.V2 != "" {
		lineText = strings.Join(p[:4], ", ")
	} else if line.V1 != "" {
		lineText = strings.Join(p[:3], ", ")
	} else if line.V0 != "" {
		lineText = strings.Join(p[:2], ", ")
	}

	persist.LoadPolicyLine(lineText, model)
}

// LoadPolicy loads policy from database.
func (a *Adapter) LoadPolicy(model model.Model) error {
	if lines, err := zd.Select[CasbinRule](nil, nil); err != nil {
		return err
	} else {
		for _, line := range lines {
			loadPolicyLine(line, model)
		}
	}
	return nil
}

func (a *Adapter) genPolicyLine(ptype string, rule []string) CasbinRule {
	line := CasbinRule{Ptype: ptype}

	l := len(rule)
	if l > 0 {
		line.V0 = rule[0]
	}
	if l > 1 {
		line.V1 = rule[1]
	}
	if l > 2 {
		line.V2 = rule[2]
	}
	if l > 3 {
		line.V3 = rule[3]
	}
	if l > 4 {
		line.V4 = rule[4]
	}
	if l > 5 {
		line.V5 = rule[5]
	}
	return line
}

// SavePolicy saves policy to database.
func (a *Adapter) SavePolicy(model model.Model) error {
	if err := zd.DropTable[CasbinRule](); err != nil {
		return err
	}
	if err := zd.CreateTable[CasbinRule](); err != nil {
		return err
	}

	lines := make([]CasbinRule, 0)

	for ptype, ast := range model["p"] {
		for _, rule := range ast.Policy {
			line := a.genPolicyLine(ptype, rule)
			lines = append(lines, line)
		}
	}

	for ptype, ast := range model["g"] {
		for _, rule := range ast.Policy {
			line := a.genPolicyLine(ptype, rule)
			lines = append(lines, line)
		}
	}

	// check whether the policy is empty
	if len(lines) == 0 {
		return nil
	}
	return zd.Insert(lines...)
}

// AddPolicy adds a policy rule to the storage.
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
	line := a.genPolicyLine(ptype, rule)
	return zd.Insert(line)
}

// AddPolicies adds multiple policy rule to the storage.
func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error {
	return zd.Transaction(func() error {
		for _, rule := range rules {
			line := a.genPolicyLine(ptype, rule)
			if err := zd.Insert(line); err != nil {
				return err
			}
		}
		return nil
	})
}

// RemovePolicy removes a policy rule from the storage.
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
	line := a.genPolicyLine(ptype, rule)
	_, err := zd.Delete[CasbinRule](line.toMap())
	return err
}

// RemovePolicies removes multiple policy rule from the storage.
func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error {
	return zd.Transaction(func() error {
		for _, rule := range rules {
			line := a.genPolicyLine(ptype, rule)
			if _, err := zd.Delete[CasbinRule](line.toMap()); err != nil {
				return nil
			}
		}
		return nil
	})
}

// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
	line := CasbinRule{Ptype: ptype}
	where := map[string]any{"Ptype": ptype}
	idx := fieldIndex + len(fieldValues)
	if fieldIndex <= 0 && idx > 0 {
		line.V0 = fieldValues[0-fieldIndex]
		where["V0"] = line.V0
	}
	if fieldIndex <= 1 && idx > 1 {
		line.V1 = fieldValues[1-fieldIndex]
		where["V1"] = line.V1
	}
	if fieldIndex <= 2 && idx > 2 {
		line.V2 = fieldValues[2-fieldIndex]
		where["V2"] = line.V2
	}
	if fieldIndex <= 3 && idx > 3 {
		line.V3 = fieldValues[3-fieldIndex]
		where["V3"] = line.V3
	}
	if fieldIndex <= 4 && idx > 4 {
		line.V4 = fieldValues[4-fieldIndex]
		where["V4"] = line.V4
	}
	if fieldIndex <= 5 && idx > 5 {
		line.V5 = fieldValues[5-fieldIndex]
		where["V5"] = line.V5
	}
	_, err := zd.Delete[CasbinRule](where)
	return err
}

// LoadFilteredPolicy loads only policy rules that match the filter.
func (a *Adapter) LoadFilteredPolicy(model model.Model, filter interface{}) error {
	filterValue, ok := filter.(Filter)
	if !ok {
		return errors.New("invalid filter type")
	}

	if lines, err := zd.Select[CasbinRule](nil, filterValue.toMap()); err != nil {
		return err
	} else {
		for _, line := range lines {
			loadPolicyLine(line, model)
		}
		a.isFiltered = true
	}
	return nil
}

// IsFiltered returns true if the loaded policy has been filtered.
func (a *Adapter) IsFiltered() bool {
	return a.isFiltered
}

// UpdatePolicy update oldRule to newPolicy permanently
func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error {
	oRule := a.genPolicyLine(ptype, oldRule)
	nRule := a.genPolicyLine(ptype, newPolicy)
	if _, err := zd.UpdateMap[CasbinRule](oRule.toMap(), nRule.toMap()); err != nil {
		return err
	}
	return nil
}

// UpdatePolicies updates some policy rules to storage, like db, redis.
func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error {
	return zd.Transaction(func() error {
		for i, oldRule := range oldRules {
			nRule, oRule := a.genPolicyLine(ptype, newRules[i]), a.genPolicyLine(ptype, oldRule)
			if _, err := zd.UpdateMap[CasbinRule](oRule.toMap(), nRule.toMap()); err != nil {
				return err
			}
		}
		return nil
	})
}

func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) {
	// UpdateFilteredPolicies deletes old rules and adds new rules.
	line := &CasbinRule{}

	line.Ptype = ptype
	if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) {
		line.V0 = fieldValues[0-fieldIndex]
	}
	if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) {
		line.V1 = fieldValues[1-fieldIndex]
	}
	if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) {
		line.V2 = fieldValues[2-fieldIndex]
	}
	if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) {
		line.V3 = fieldValues[3-fieldIndex]
	}
	if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) {
		line.V4 = fieldValues[4-fieldIndex]
	}
	if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) {
		line.V5 = fieldValues[5-fieldIndex]
	}

	newP := make([]CasbinRule, 0, len(newPolicies))
	for _, newRule := range newPolicies {
		newP = append(newP, a.genPolicyLine(ptype, newRule))
	}

	oldP, err := zd.Select[CasbinRule](nil, line.toMap())
	if err != nil {
		return nil, err
	}
	if err := zd.Transaction(func() error {
		if _, err := zd.Delete[CasbinRule](line.toMap()); err != nil {
			return err
		}
		return zd.Insert(newP...)
	}); err != nil {
		return nil, err
	}

	// return deleted rulues
	oldPolicies := make([][]string, 0)
	for _, v := range oldP {
		oldPolicy := v.toStringPolicy()
		oldPolicies = append(oldPolicies, oldPolicy)
	}
	return oldPolicies, nil
}

func (c *CasbinRule) toStringPolicy() []string {
	policy := make([]string, 0)
	if c.Ptype != "" {
		policy = append(policy, c.Ptype)
	}
	if c.V0 != "" {
		policy = append(policy, c.V0)
	}
	if c.V1 != "" {
		policy = append(policy, c.V1)
	}
	if c.V2 != "" {
		policy = append(policy, c.V2)
	}
	if c.V3 != "" {
		policy = append(policy, c.V3)
	}
	if c.V4 != "" {
		policy = append(policy, c.V4)
	}
	if c.V5 != "" {
		policy = append(policy, c.V5)
	}
	return policy
}

func (c *CasbinRule) toMap() map[string]any {
	mp := map[string]any{"ptype": c.Ptype}
	if c.V0 != "" {
		mp["V0"] = c.V0
	}
	if c.V1 != "" {
		mp["V1"] = c.V1
	}
	if c.V2 != "" {
		mp["V2"] = c.V2
	}
	if c.V3 != "" {
		mp["V3"] = c.V3
	}
	if c.V4 != "" {
		mp["V4"] = c.V4
	}
	if c.V5 != "" {
		mp["V5"] = c.V5
	}
	return mp
}
